package io.netopen.hotbitmapgg.view;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import io.netopen.view.ResourceTable;
import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorValue;
import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.render.*;
import ohos.agp.utils.Color;
import ohos.agp.utils.Matrix;
import ohos.agp.utils.RectFloat;
import ohos.agp.utils.TextAlignment;
import ohos.app.Context;
import ohos.global.resource.NotExistException;
import ohos.global.resource.Resource;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;
import ohos.media.image.common.Size;

/**
 * Created by hcc on 16/9/1 22:21
 * 100332338@qq.com
 * <p/>
 * 仿芝麻信用的圆环实现(旧版)
 */
public class OldCreditSesameView extends Component implements Component.DrawTask, Component.EstimateSizeListener,Component.BindStateChangedListener  {

  // 最外层圆环渐变色环颜色
  private final Color[] mColors = new Color[] {
      Color.RED,
      Color.YELLOW,
      Color.GREEN
  };

  //圆环的信用等级文本
  private static final String[] text = {
      "950", "极好",
      "700", "优秀",
      "650", "良好",
      "600", "中等",
      "550", "较差",
      "350"
  };

  //中间进度颜色
  private static final int GREEN_COLOR = 0xFF06C494;

  private static final Color GRAY_COLOR = Color.LTGRAY;

  // 宽度
  private int width;

  // 高度
  private int height;

  // 半径
  private int radius;

  // 指针图片
  private PixelMap mBitmap;

  // 指针图片宽度
  private int mBitmapWidth;

  // 指针图片高度
  private int mBitmapHeight;

  // 最外层渐变圆环画笔
  private Paint mGradientRingPaint;

  // 大刻度画笔
  private Paint mSmallCalibrationPaint;

  // 小刻度画笔
  private Paint mBigCalibrationPaint;

  // 中间进度圆环画笔
  private Paint mMiddleRingPaint;

  // 内虚线圆环画笔
  private Paint mInnerRingPaint;

  // 外层圆环文本画笔
  private Paint mTextPaint;

  // 中间进度圆环画笔
  private Paint mMiddleProgressPaint;

  // 指针图片画笔
  private Paint mPointerBitmapPaint;

  //中间文本画笔
  private Paint mCenterTextPaint;

  // 绘制外层圆环的矩形
  private RectFloat mOuterArc;

  // 绘制内层圆环的矩形
  private RectFloat mInnerArc;

  // 绘制中间圆环的矩形
  private RectFloat mMiddleArc;

  // 中间进度圆环的值
  private float oval4;

  // 绘制中间进度圆环的矩形
  private RectFloat mMiddleProgressArc;

  // 圆环起始角度
  private static final float mStartAngle = 115f;

  // 圆环结束角度
  private static final float mEndAngle = 230f;

  // 指针全部进度
  private float mTotalAngle = 230f;

  // 指针当前进度
  private float mCurrentAngle = 0f;

  // View默认宽高值
  private int defaultSize;

  // 最小数字
  private int mMinNum = 0;

  // 最大数字
  private int mMaxNum = 950;

  //信用等级
  private String sesameLevel = "";

  //评估时间
  private String evaluationTime = "";



  public OldCreditSesameView(Context context) {

    this(context, null);
  }


  public OldCreditSesameView(Context context, AttrSet attrs) {

    this(context, attrs, 0);
  }


  public OldCreditSesameView(Context context, AttrSet attrs, int defStyleAttr) {

    super(context, attrs, defStyleAttr);
    addDrawTask(this);
    setEstimateSizeListener(this);
    setBindStateChangedListener(this);
    init();
  }


  /**
   * 初始化
   */
  private void init() {
    //设置默认宽高值
    defaultSize = 250;

    //最外层圆环渐变画笔设置
    mGradientRingPaint = new Paint();
    //设置圆环渐变色渲染
    //mGradientRingPaint.serX(new PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP));
    float position[] = { 0.1f, 0.3f, 0.8f };
    Shader mShader = new SweepShader(width / 2, radius, mColors, position);
    mGradientRingPaint.setShader(mShader, Paint.ShaderType.SWEEP_SHADER);
    mGradientRingPaint.setStrokeCap(Paint.StrokeCap.ROUND_CAP);
    mGradientRingPaint.setStyle(Paint.Style.STROKE_STYLE);
    mGradientRingPaint.setStrokeWidth(40);

    //最外层圆环大小刻度画笔设置
    mSmallCalibrationPaint = new Paint();
    mSmallCalibrationPaint.setColor(Color.WHITE);
    mSmallCalibrationPaint.setStyle(Paint.Style.STROKE_STYLE);
    mSmallCalibrationPaint.setStrokeWidth(1);

    mBigCalibrationPaint = new Paint();
    mBigCalibrationPaint.setColor(Color.WHITE);
    mBigCalibrationPaint.setStyle(Paint.Style.STROKE_STYLE);
    mBigCalibrationPaint.setStrokeWidth(4);

    //中间圆环画笔设置
    mMiddleRingPaint = new Paint();
    mMiddleRingPaint.setStyle(Paint.Style.STROKE_STYLE);
    mMiddleRingPaint.setStrokeCap(Paint.StrokeCap.ROUND_CAP);
    mMiddleRingPaint.setStrokeWidth(5);
    mMiddleRingPaint.setColor(GRAY_COLOR);

    //内层圆环画笔设置
    mInnerRingPaint = new Paint();
    mInnerRingPaint.setStyle(Paint.Style.STROKE_STYLE);
    mInnerRingPaint.setStrokeCap(Paint.StrokeCap.ROUND_CAP);
    mInnerRingPaint.setStrokeWidth(4);
    mInnerRingPaint.setColor(GRAY_COLOR);
    PathEffect mPathEffect = new PathEffect(new float[] { 5, 5, 5, 5 }, 1);
    mInnerRingPaint.setPathEffect(mPathEffect);

    //外层圆环文本画笔设置
    mTextPaint = new Paint();
    mTextPaint.setColor(GRAY_COLOR);
    mTextPaint.setTextSize(30);

    //中间文字画笔设置
    mCenterTextPaint = new Paint();
    mCenterTextPaint.setTextAlign(TextAlignment.CENTER);

    //中间圆环进度画笔设置
    mMiddleProgressPaint = new Paint();
    mMiddleProgressPaint.setColor(Color.GRAY);
    mMiddleProgressPaint.setStrokeCap(Paint.StrokeCap.ROUND_CAP);
    mMiddleProgressPaint.setStrokeWidth(5);
    mMiddleProgressPaint.setStyle(Paint.Style.STROKE_STYLE);

    //指针图片画笔
    mPointerBitmapPaint = new Paint();
    mPointerBitmapPaint.setColor(Color.GREEN);

    //获取指针图片
    mBitmap = getPixelMap(getContext(), ResourceTable.Media_ic_pointer);
    mBitmapHeight = mBitmap.getImageInfo().size.height;
    mBitmapWidth = mBitmap.getImageInfo().size.width;
    pos = new float[2];
  }

  public static PixelMap getPixelMap(Context context, int id) {
    ImageSource.SourceOptions options = new ImageSource.SourceOptions();
    options.formatHint = "image/png";
    ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
    try {
      Resource asset = context.getResourceManager().getResource(id);
      ImageSource source = ImageSource.create(asset, options);
      return source.createPixelmap(decodingOptions);
    } catch (IOException | NotExistException e) {
      //LogUtil.error(AttrUtils.class.getName(), e.getMessage());
    }
    return null;
  }

  @Override
  public boolean onEstimateSize(int i, int i1) {
    //setEstimatedSize(resolveMeasure(i, defaultSize),resolveMeasure(i1,defaultSize));
    return false;
  }


  @Override
  public void onComponentUnboundFromWindow(Component component) {

  }
  @Override
  public void onComponentBoundToWindow(Component component) {

    width = getWidth();
    height = getHeight();

    //确定View宽高
    width = width;
    height = height;

    //圆环半径
    radius = width / 2;

    //外层圆环
    float oval1 = radius - mGradientRingPaint.getStrokeWidth() * 0.5f;
    mOuterArc = new RectFloat(-oval1, -oval1, oval1, oval1);

    //中间和内层圆环
    float oval2 = radius * 5 / 8;
    float oval3 = radius * 3 / 4;
    mInnerArc = new RectFloat(-oval2, -oval2, oval2, oval2);
    mMiddleArc = new RectFloat(-oval3, -oval3, oval3, oval3);

    //中间进度圆环
    oval4 = radius * 6 / 8;
    mMiddleProgressArc = new RectFloat(-oval4, -oval4, oval4, oval4);

  }


  @Override
  public void onDraw(Component component, Canvas canvas) {

    drawArc(canvas);
    drawCalibration(canvas);
    drawArcText(canvas);
    drawCenterText(canvas);
    drawBitmapProgress(canvas);
  }

  //当前点的实际位置
  private float[] pos;

  //当前点的tangent值
  private float[] tan;
  /**
   * 绘制中间进度和指针图片
   */
  private void drawBitmapProgress(Canvas canvas) {

    canvas.save();
    canvas.translate(radius, radius);
    canvas.rotate(270);
    canvas.drawArc(mMiddleProgressArc, new Arc(-mStartAngle, mCurrentAngle, false), mMiddleProgressPaint);
    canvas.rotate(68 + mCurrentAngle);
    Matrix matrix = new Matrix();
    matrix.preTranslate(-oval4 - mBitmapWidth * 3 / 8, -mBitmapHeight / 2);
    canvas.restore();
  }
  private static PixelMap createPixelMap(int width, int height) {

    PixelMap pixelMap;

    PixelMap.InitializationOptions options =

            new PixelMap.InitializationOptions();

    options.size = new Size(width, height);

    options.pixelFormat = PixelFormat.ARGB_8888;

    options.editable = true;

    pixelMap = PixelMap.create(options);

    return pixelMap;

  }

  /**
   * 绘制中间文本内容
   */
  private void drawCenterText(Canvas canvas) {

    //绘制Logo
    mCenterTextPaint.setTextSize(30);
    mCenterTextPaint.setColor(Color.LTGRAY);
    canvas.drawText(mCenterTextPaint,"BETA", radius, radius - 130);

    //绘制信用分数
    mCenterTextPaint.setColor(Color.GREEN);
    mCenterTextPaint.setTextSize(200);
    mCenterTextPaint.setStyle(Paint.Style.FILL_STYLE);
    canvas.drawText(mCenterTextPaint,String.valueOf(mMinNum), radius, radius + 70);

    //绘制信用级别
    mCenterTextPaint.setColor(Color.GREEN);
    mCenterTextPaint.setTextSize(80);
    canvas.drawText(mCenterTextPaint,sesameLevel, radius, radius + 160);

    //绘制评估时间
    mCenterTextPaint.setColor(Color.LTGRAY);
    mCenterTextPaint.setTextSize(30);
    canvas.drawText(mCenterTextPaint,evaluationTime, radius, radius + 205);
  }


  /**
   * 绘制圆弧上的文本
   */
  private void drawArcText(Canvas canvas) {

    for (int i = 0; i <= 10; i++) {
      canvas.save();
      canvas.rotate(-(-10 + 20 * i - 88), radius, radius);
      canvas.drawText(mTextPaint,text[i], radius - 10, radius * 3 / 16);
      canvas.restore();
    }
  }


  /**
   * 绘制大小刻度线
   */
  private void drawCalibration(Canvas canvas) {

    int dst = (int) (2 * radius - mGradientRingPaint.getStrokeWidth());
    for (int i = 0; i <= 50; i++) {
      canvas.save();
      canvas.rotate(-(-10 + 4 * i), radius, radius);
      if (i % 10 == 0) {
        canvas.drawLine(dst, radius, 2 * radius, radius, mBigCalibrationPaint);
      } else {
        canvas.drawLine(dst, radius, 2 * radius, radius, mSmallCalibrationPaint);
      }
      canvas.restore();
    }
  }


  /**
   * 分别绘制外层 中间 内层圆环
   */
  private void drawArc(Canvas canvas) {

    canvas.save();
    canvas.translate(width / 2, height / 2);

    //画最外层的渐变圆环
    canvas.rotate(140);
    canvas.drawArc(mOuterArc, new Arc(-mStartAngle, -mEndAngle, false), mGradientRingPaint);

    //绘制内圈圆形
    canvas.drawArc(mInnerArc, new Arc(-mStartAngle, -mEndAngle, false), mInnerRingPaint);
    canvas.drawArc(mMiddleArc, new Arc(-mStartAngle, -mEndAngle, false), mMiddleRingPaint);
    canvas.restore();
  }


  /**
   * 设置芝麻信用数据
   */
  public void setSesameValues(int num) {

    if (num <= 350) {
      mMaxNum = num;
      mTotalAngle = 0f;
      sesameLevel = "信用较差";
      evaluationTime = "评估时间:" + getCurrentTime();
    } else if (num <= 550) {
      mMaxNum = num;
      mTotalAngle = (num - 350) * 80 / 400f + 13;
      sesameLevel = "信用较差";
      evaluationTime = "评估时间:" + getCurrentTime();
    } else if (num <= 700) {
      mMaxNum = num;
      if (num > 550 && num <= 600) {
        sesameLevel = "信用中等";
        mTotalAngle = (num - 550) * 120 / 150f + 43;
      } else if (num > 600 && num <= 650) {
        sesameLevel = "信用良好";
        mTotalAngle = (num - 550) * 120 / 150f + 45;
      } else {
        sesameLevel = "信用优秀";
        mTotalAngle = (num - 550) * 120 / 150f + 48;
      }
      evaluationTime = "评估时间:" + getCurrentTime();
    } else if (num <= 950) {
      mMaxNum = num;
      mTotalAngle = (num - 700) * 40 / 250f + 185;
      sesameLevel = "信用极好";
      evaluationTime = "评估时间:" + getCurrentTime();
    } else {
      mTotalAngle = 240f;
    }

    startRotateAnim();
  }


  boolean b;
  float d;
  float startAngle;
  int startNum;
  int dNum;
  public void startRotateAnim() {
    startAngle=mCurrentAngle;
    if(mCurrentAngle<mTotalAngle){
      b=true;
      d=mTotalAngle-mCurrentAngle;
    }else{
      b=false;
      d=mCurrentAngle-mTotalAngle;
    }
    AnimatorValue mAngleAnim = new AnimatorValue();
    mAngleAnim.setCurveType(Animator.CurveType.ACCELERATE_DECELERATE);
    mAngleAnim.setDuration(3000);
    mAngleAnim.setValueUpdateListener(new AnimatorValue.ValueUpdateListener() {
      @Override
      public void onUpdate(AnimatorValue animatorValue, float v) {//0-1
        if(b){
          mCurrentAngle =startAngle+d*v;
        }else{
          mCurrentAngle =startAngle-d*v;
        }

        invalidate();
      }
    });
    mAngleAnim.start();
    startNum=mMinNum;
    // mMinNum = 350;
    if(mMinNum<mMaxNum){
      b=true;
      dNum=mMaxNum-mMinNum;
    }else{
      b=false;
      dNum=mMinNum-mMaxNum;
    }
    AnimatorValue mNumAnim = new AnimatorValue();
    mNumAnim.setDuration(3000);
    mNumAnim.setCurveType(Animator.CurveType.LINEAR);
    mNumAnim.setValueUpdateListener(new AnimatorValue.ValueUpdateListener() {
      @Override
      public void onUpdate(AnimatorValue animatorValue, float v) {
        if(b){
          mMinNum =startNum+(int)(dNum*v);
        }else{
          mMinNum =startNum-(int)(dNum*v);
        }

        invalidate();
      }
    });
    mNumAnim.start();
  }


  /**
   * 获取当前时间
   */
  public String getCurrentTime() {
    SimpleDateFormat format = new SimpleDateFormat("yyyy:MM:dd");
    return format.format(new Date());
  }
}
